#!/usr/bin/env bash

if ! type dvm &> /dev/null
then
  return
fi

_dvm_has_active_version() {
  echo "$PATH" | grep -q "$DVM_DIR/versions"
}

_dvm_add_versions_to_opts() {
  if [ ! -d "$DVM_DIR/versions" ]
  then
    return
  fi

  if [ -z "$(ls -A "$DVM_DIR/versions")" ]
  then
    return 0
  fi

  for path in "$DVM_DIR/versions"/*
  do
    if [ -f "$path/deno" ]
    then
      version=${path##*/}

      opts="$opts $version"
    fi
  done
}

_dvm_add_aliases_to_opts() {
  if [ ! -d "$DVM_DIR/aliases" ]
  then
    return
  fi

  if [ -z "$(ls -A "$DVM_DIR/aliases")" ]
  then
    return 0
  fi

  for path in "$DVM_DIR/aliases"/*
  do
    alias_name=${path##*/}
    version=$(cat "$path")

    if [ -f "$DVM_DIR/versions/$version/deno" ]
    then
      opts="$opts $alias_name"
    fi
  done
}

_dvm_completion() {
  local cur
  local prev

  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  prev="${COMP_WORDS[COMP_CWORD-1]}"
  opts=""

  case "$prev" in
  use|uninstall|run|which)
    if [ "$prev" = "which" ] && _dvm_has_active_version
    then
      opts="current"
    fi

    _dvm_add_versions_to_opts
    _dvm_add_aliases_to_opts
    ;;
  unalias)
    _dvm_add_aliases_to_opts
    ;;
  doctor)
    opts="--fix"
    ;;
  dvm|"$DVM_DIR/dvm.sh")
    if [[ ${cur} == -* ]]
    then
      opts="--help --version -h"
    else
      opts="alias clean current deactivate doctor help install list list-remote
        ls ls-remote run upgrade unalias uninstall use which"
    fi
    ;;
  *)
    opts=""
    ;;
  esac

  # shellcheck disable=SC2207
  COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
}

if [ -n "$ZSH_NAME" ]
then
  autoload -U +X compinit && compinit
  autoload -U +X bashcompinit && bashcompinit
fi

complete -F _dvm_completion dvm
